﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;
using Microsoft.Practices.Unity;
using System;

namespace AsNum.Common.EntLib.Validation {

    /// <summary>
    /// 
    /// </summary>
    public class ClientAdapterFactory {

        /// <summary>
        /// 依赖注入容器
        /// </summary>
        private static IUnityContainer container = new UnityContainer();

        /// <summary>
        /// 
        /// </summary>
        static ClientAdapterFactory() {
            //查找当前所有继承自 BaseClientAdapter 的 Adapter , 并注册
            var types = Assembly.GetCallingAssembly().GetExportedTypes().Where(t => t.IsSubclassOf(typeof(BaseClientAdapter)) && !t.IsAbstract);
            var fromType = typeof(BaseClientAdapter);
            foreach (var type in types) {
                var name = type.GetProperty("ValidatorData").PropertyType.Name;
                container.RegisterType(fromType, type, name);
            }
        }

        /// <summary>
        /// 根据 ValidatorData 获取对应的适配器
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static BaseClientAdapter GetAdapter(ValidatorData data , Dictionary<string , Tuple<string , string>> map , bool isSub = false) {
            string nameToCheck = data.GetType().Name;
            if (container.IsRegistered<BaseClientAdapter>(nameToCheck)) {
                return container.Resolve<BaseClientAdapter>(nameToCheck, new ParameterOverride("data", data), new ParameterOverride("map", map), new ParameterOverride("isSub", isSub));
            } else {
                // TODO : 不存在对应的适配器
                return null;
            }
        }
    }
}
